import UrlUtil from "@/util/UrlUtil.js"

function preview(fileUrl, type){
	let url = UrlUtil.decode(fileUrl);
	
	if(type == 'picture' || url.endsWith('.pdf')){
		uni.navigateTo({
			url: '/pages/common/preview?src='+encodeURIComponent(url)
		})
	} else {
		//
		doDownload(url);
	}
}

function doDownload(url){
	url = UrlUtil.decode(url);
	let that = this;
	uni.showLoading({
		title: '传递中请稍等...',
		mask: true
	})
	
	uni.downloadFile({
		url: url,//下载地址接口返回
		success: (data) => {
			if (data.statusCode === 200) {
				//文件保存到本地
				let filePath = data.tempFilePath;
				uni.getFileSystemManager().saveFile({
					tempFilePath: filePath, //临时路径
					success:function(res){
						//预览
						uni.openDocument({
							filePath: res.savedFilePath,
							showMenu: true,
							success: function (res) {
								console.log('打开文档成功');
							},
							complete() {
								uni.hideLoading();
							}
						});
					},
					complete(){
						uni.hideLoading();
					}
				})
			} else {
				uni.hideLoading();
			}
		},
		fail: (err) => {
			uni.hideLoading();
			uni.showToast({
				icon: 'none',
				mask: true,
				title: '失败请重新下载',
			});
		},
	});
}

export default { preview, doDownload }